import java.io.EOFException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.HashMap;
import java.util.LinkedList;

public class DatabaseThread implements Runnable{
	private LinkedList<Measurement> queue;
	//All stations have their own file, this is saved in this HashMap
	private HashMap<Integer, RandomAccessFile> files;
	
	public DatabaseThread() {
		files = new HashMap<Integer, RandomAccessFile>();
		queue = new LinkedList<Measurement>();		
		new File("database").mkdir();
	}
	
	
	public LinkedList<Measurement> searchStationData(int stn, int limit) {
		System.out.println("Searching for stn:" + stn + ", limit: " + limit);
		LinkedList<Measurement> results = new LinkedList<Measurement>();
		
		if(files.containsKey(stn)) {
			//Get the station file
			RandomAccessFile raf = files.get(stn);
			long i = 0;
			try {
				while(i < raf.length()-1 && results.size() != limit) {		
					raf.seek(i);
					try {
					String inputline = raf.readUTF();
					String[] row = inputline.split(";");					
						Measurement m = new Measurement();
						m.setStn(Integer.parseInt(row[0]));
						m.setDate(Integer.parseInt(row[1]));
						m.setTime(Integer.parseInt(row[2]));
						m.setTemp(Float.parseFloat(row[3]));
						m.setDewp(Float.parseFloat(row[4]));
						m.setStp(Float.parseFloat(row[5]));
						m.setSlp(Float.parseFloat(row[6]));
						m.setVisib(Float.parseFloat(row[7]));
						m.setWdsp(Float.parseFloat(row[8]));
						m.setPrcp(Float.parseFloat(row[9]));
						m.setSndp(Float.parseFloat(row[10]));
						m.setFrshtt(Integer.parseInt(row[11]));
						m.setCldc(Float.parseFloat(row[12]));
						m.setWnddir(Integer.parseInt(row[13]));
						results.addLast(m);
					}
					catch (EOFException e) {
						
					}
						i++;
					
				}
			} catch (IOException e) {
				System.out.println("Unable to search!");
				e.printStackTrace();
			}
			return results;
		}
		return null;
	}
	
	private void createStationFile(int stn) {
		try {
			String path = new java.io.File(".").getCanonicalPath();
			File f = new File(path +"\\database\\"+ stn + ".data");
			files.put(stn, new RandomAccessFile(f, "rw"));
			System.out.println("Station file created!");
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public synchronized void add(Measurement measurement) {
		queue.addLast(measurement);
		int stn = measurement.getStn();
		if(!files.containsKey(stn)) {
			createStationFile(stn);
		}
		System.out.println("Measurement added to queue");
		notify();
	}
	
	public synchronized void waitForMeasurements() {
		while (queue.isEmpty()) {
			try {
				System.out.println("Waiting for measurements...");
				
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
			try {
				
				Measurement m = queue.removeFirst();
				RandomAccessFile raf = files.get(m.getStn());
			    // Seek in beginning of file
			    raf.seek(raf.length());
	
			    // Append to the end
			    String outputLine = m.getDatastring();
			    raf.writeUTF(outputLine);
			    System.out.println("Measurement writen to file");
			} catch (IOException e) {
				System.out.println("Failed to write to file!");
			}

		
	}
	
	public void run() {
		while(true) {
			waitForMeasurements();
		}
		
	}
	
	

}
